package com.goldapp.imagenesparawhatsapp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;



import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.google.ads.InterstitialAd;
import com.google.analytics.tracking.android.EasyTracker;


import android.os.StrictMode;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;



public class Main extends Activity implements OnClickListener, AdListener {

	Random rnd = new Random();
	ImageView principal, derecha, izquierda, save,  tw;
	int cont = 1, contpubli = 0;
	File directorio, sdCard, file;
	private AdView adView;
	SharedPreferences appPref;
	boolean isFirstTime = true;
	public static final String MY_PUBLISHER_ID = "ca-app-pub-7828120634029283/6036999952";
	private static final String LOG_TAG = "IQ!";
	private InterstitialAd interstitialAd;
	AdRequest adRequest = new AdRequest();
	Metodos metodo = new Metodos();
	


	@SuppressLint("CutPasteId")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.main);

		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);

		
		metodo.Imagenes(cont);

		// **********************************************************************+

		principal = (ImageView) findViewById(R.id.principal);
		derecha = (ImageView) findViewById(R.id.derecha);
		izquierda = (ImageView) findViewById(R.id.izquierda);
		save = (ImageView) findViewById(R.id.save);
		tw = (ImageView) findViewById(R.id.tw);

		derecha.setOnClickListener(this);
		izquierda.setOnClickListener(this);
		save.setOnClickListener(this);
		tw.setOnClickListener(this);
		

		principal.setImageResource(R.drawable.img001 + metodo.Imagenes(cont));

		// PUBLICIDAD DE GOOGLE EL INTERSTITIAL EL Q DA PLATA XD

		interstitialAd = new InterstitialAd(this, MY_PUBLISHER_ID); // Create an
																	// ad.
		interstitialAd.setAdListener(this); // Set the AdListener.

		// adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
		interstitialAd.loadAd(adRequest);
		

	}


	@Override
	public void onStart() {
		super.onStart();
		// The rest of your onStart() code.
		EasyTracker.getInstance(this).activityStart(this); // Add this method.
	}

	@Override
	public void onStop() {
		super.onStop();
		// The rest of your onStop() code.
		EasyTracker.getInstance(this).activityStop(this); // Add this method.
	}

	@Override
	public void onDestroy() {
		if (adView != null)
			adView.destroy();
		super.onDestroy();

	}

	@Override
	public void onClick(View v) {

		// se llama a la clase para ver de donde es el usuario y mostrar la ad

		switch (v.getId()) {

		case R.id.derecha:
			cont++;
			int numimagen = R.drawable.img001 + metodo.Imagenes(cont);
			contpubli++;
			principal.setImageResource(numimagen);
			System.out.println("EL CONTADOR VA POR: " + contpubli);

			if (contpubli >= 12) {

				if (interstitialAd.isReady()) {

					interstitialAd.show();
					interstitialAd.loadAd(adRequest);

				}

				contpubli = 1;
			} else {
				Log.d(LOG_TAG, "Interstitial ad was not ready to be shown.");
			}

			break;

		case R.id.izquierda:

			cont--;
			int hola = R.drawable.img001 + metodo.Imagenes(cont);
			if (cont <= 0) {
				System.out.println("CONTADOR NO VALIDO PARA IMAGEN  " + cont);
				cont++;
			} else {
				principal.setImageResource(hola);
			}
			break;

		case R.id.save:
			
			
			
		//	metodo.guardar(cont, principal);
			
		
			// se revisa si se puede escribir en la memoria
			boolean permiso = false;
			Guardar guardar = new Guardar();
			permiso = guardar.comprobarSd();
			if (permiso == true) {

				// Retrieve the image from the res folder
				BitmapDrawable drawable = (BitmapDrawable) principal
						.getDrawable();
				Bitmap bitmap1 = drawable.getBitmap();

				// Find the SD Card path
				File filepath = Environment.getExternalStorageDirectory();

				// Create a new folder in SD Card
				File dir = new File(filepath.getAbsolutePath()
						+ "/WhatSappIMGN/");

				if (!dir.exists()) {
					dir.mkdirs();

				}

				// comprueba si la imagen existe
				String img = "img0" + metodo.Imagenes(cont) + ".jpg";
				File imgexiste = new File(filepath.getAbsoluteFile()
						+ "/WhatSappIMGN/" + img);
				if (!imgexiste.exists()) {
					// Create a name for the saved image
					file = new File(dir, img);

					try {

						OutputStream output;

						output = new FileOutputStream(file);

						// Compress into png format image from 0% - 100%
						bitmap1.compress(Bitmap.CompressFormat.JPEG, 100,
								output);
						output.flush();
						output.close();

						addImageToGallery(file.getAbsolutePath(), Main.this);
						Toast.makeText(getBaseContext(),
								"Imagen copiada a SDCard", Toast.LENGTH_LONG)
								.show();
					}

					catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				else {
					Toast.makeText(getBaseContext(), "Imagen Ya existe",
							Toast.LENGTH_LONG).show();
				}

			} else {
				Toast.makeText(
						getBaseContext(),
						"El almacenamineto externio no se encuentra disponible",
						Toast.LENGTH_LONG).show();
			}



			break;

		case R.id.tw:
			
		share("facebook");

			break;
		}
	}

	
	@SuppressLint("DefaultLocale")
	void share(String nameApp) {
		  try
		  {
		      List<Intent> targetedShareIntents = new ArrayList<Intent>();
		      Intent share = new Intent(android.content.Intent.ACTION_SEND);
		      share.setType("image/jpeg");
		      List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
		      if (!resInfo.isEmpty()){
		          for (ResolveInfo info : resInfo) {
		              Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
		              targetedShare.setType("image/jpeg"); // put here your mime type
		              if (info.activityInfo.packageName.toLowerCase().contains("facebook") || info.activityInfo.name.toLowerCase().contains("facebook") ||
		            		  info.activityInfo.packageName.toLowerCase().contains("gmail") || info.activityInfo.name.toLowerCase().contains("gmail") ||
		            		  info.activityInfo.packageName.toLowerCase().contains("com.twitter.android") || info.activityInfo.name.toLowerCase().contains("com.twitter.android") ||
		            		  info.activityInfo.packageName.toLowerCase().contains("com.whatsapp") || info.activityInfo.name.toLowerCase().contains("com.whatsapp")
		            		  ) {
		                  targetedShare.putExtra(Intent.EXTRA_SUBJECT, "Imagenes Whatsapp");
		                  
		                  targetedShare.putExtra(Intent.EXTRA_STREAM, metodo.rutaImg(principal));
		                  if(info.activityInfo.packageName == "com.twitter.android"){
		                	  targetedShare.putExtra(Intent.EXTRA_TEXT,"Siguenos en twitter @WhatsappImagene Descarganos http://goo.gl/QaB9WI");
		                  }
		                  else{
		                	  targetedShare.putExtra(Intent.EXTRA_TEXT,"Gracias por usar @WhatsappImagene Descarganos http://goo.gl/QaB9WI");
		                  }
		                  targetedShare.setPackage(info.activityInfo.packageName);
		                  targetedShareIntents.add(targetedShare);
		             }
		          }
		          Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Selecciona tu app");
		          chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
		          startActivity(chooserIntent);
		      }
		  }
		  catch(Exception e){
		      Log.v("VM","Exception while sending image on" + nameApp + " "+  e.getMessage());
		  }
		}
	
	

	

	public static void addImageToGallery(final String filePath,
			final Context context) {

		ContentValues values = new ContentValues();

		values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
		values.put(Images.Media.MIME_TYPE, "image/jpeg");
		values.put(MediaStore.MediaColumns.DATA, filePath);

		context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
				values);

	}

	/** Called when an ad is clicked and about to return to the application. */
	@Override
	public void onDismissScreen(Ad ad) {
		Log.d(LOG_TAG, "onDismissScreen");
		// Toast.makeText(this, "onDismissScreen", Toast.LENGTH_SHORT).show();
	}

	/** Called when an ad was not received. */
	@Override
	public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error) {
		String message = "onFailedToReceiveAd (" + error + ")";
		Log.d(LOG_TAG, message);
		// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onLeaveApplication(Ad ad) {
		Log.d(LOG_TAG, "onLeaveApplication");

		if (ad.isReady() == true) {
			// Toast.makeText(this, "onLeaveApplication",
			// Toast.LENGTH_SHORT).show();
			interstitialAd.show();
		}
	}

	/**
	 * Called when an Activity is created in front of the app (e.g. an
	 * interstitial is shown, or an ad is clicked and launches a new Activity).
	 */
	@Override
	public void onPresentScreen(Ad v) {
		Log.d(LOG_TAG, "IMAGENES");
		System.out.println("EL CONTADOR VA POR? " + cont);
		if (v.isReady()) {
			// Toast.makeText(this, "onReceiveAd", Toast.LENGTH_SHORT).show();

			interstitialAd.show();
		}
	}

	/** Called when an ad is received. */
	@Override
	public void onReceiveAd(Ad ad) {
		Log.d(LOG_TAG, "onReceiveAd");
		if (ad.isReady()) {
		
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mnuSalir:
			finish();
			break;

		}
		return false;
	}







}
